//
//  AppDelegate.m
//  Run
//
//  Created by BetaTheta on 16/3/30.
//  Copyright © 2016年 BetaTheta. All rights reserved.
//

#import "AppDelegate.h"

#import "DYMainVC.h"
#import "TimeViewController.h"
#import "GuideVC.h"
#import <AudioToolbox/AudioToolbox.h>

static SystemSoundID audio_queue = 0;

@interface AppDelegate ()<RESideMenuDelegate, GuideVCDelegate>

@property (nonatomic, strong) UINavigationController *navi;
@property (nonatomic, retain) NSTimer *vibrate; //震动
@property (nonatomic, retain) NSTimer *musicPlay; //音乐
@property (nonatomic, retain) NSArray *musicArr;

@end

@implementation AppDelegate
void playFinished(SystemSoundID  ssID, void* clientData)
{
    AudioServicesPlaySystemSound((SystemSoundID)audio_queue);
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    self.window=[[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.window makeKeyAndVisible];
    self.window.backgroundColor= [UIColor whiteColor];
    
    
    //处理iOS8本地推送不能收到
    float sysVersion=[[UIDevice currentDevice]systemVersion].floatValue;
    if (sysVersion>=8.0) {
        UIUserNotificationType type=UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound;
        UIUserNotificationSettings *setting=[UIUserNotificationSettings settingsForTypes:type categories:nil];
        [[UIApplication sharedApplication]registerUserNotificationSettings:setting];
    } else {
        UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
    }


    
    
#pragma mark - 是否启动引导页
    NSString *Guide = [[NSUserDefaults standardUserDefaults] objectForKey:@"Guide"];
    if ([Guide isEqualToString:@"yes"]) {
        
        [self endGuide];
        
    } else {
        
        [self createGuide];
        
    }
    
    return YES;
    
}

- (void)endGuide {
    
    [self createLeftDrawer];
    
}

- (void)createGuide {
    
    NSArray *picArr = @[@"one", @"two", @"three"];
    GuideVC *guideVC = [[GuideVC alloc] initWithPicArr:picArr];
    guideVC.delegate = self;
    self.window.rootViewController = guideVC;
    
}

- (void)createLeftDrawer{
    DYMainVC *mainVC=[[DYMainVC alloc] init];
    self.navi=[[UINavigationController alloc] initWithRootViewController:mainVC];
    
    DYLeftDrawerVC *leftMenuController=[[DYLeftDrawerVC alloc] init];
    
    self.sideMenuViewController = [[RESideMenu alloc] initWithContentViewController:self.navi
                                           leftMenuViewController:leftMenuController
                                                            rightMenuViewController:nil];
    _sideMenuViewController.backgroundImage = [UIImage imageNamed:@"抽屉背景"];
    _sideMenuViewController.menuPreferredStatusBarStyle = 1;
    _sideMenuViewController.delegate = self;
    
    // 阴影设置
    _sideMenuViewController.contentViewShadowColor = [UIColor blackColor];
    _sideMenuViewController.contentViewShadowOffset = CGSizeMake(0, 0);
    _sideMenuViewController.contentViewShadowOpacity = 0.6;
    _sideMenuViewController.contentViewShadowRadius = 12;
    _sideMenuViewController.contentViewShadowEnabled = YES;
    
    self.window.rootViewController=_sideMenuViewController;
    
}

- (void)sideMenu:(RESideMenu *)sideMenu willShowMenuViewController:(UIViewController *)menuViewController
{
    NSLog(@"willShowMenuViewController: %@", NSStringFromClass([menuViewController class]));
}

- (void)sideMenu:(RESideMenu *)sideMenu didShowMenuViewController:(UIViewController *)menuViewController
{
    NSLog(@"didShowMenuViewController: %@", NSStringFromClass([menuViewController class]));
}

- (void)sideMenu:(RESideMenu *)sideMenu willHideMenuViewController:(UIViewController *)menuViewController
{
    NSLog(@"willHideMenuViewController: %@", NSStringFromClass([menuViewController class]));
}

- (void)sideMenu:(RESideMenu *)sideMenu didHideMenuViewController:(UIViewController *)menuViewController
{
    NSLog(@"didHideMenuViewController: %@", NSStringFromClass([menuViewController class]));
}



#pragma mark 程序正在前台的状态下
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
    
    if (notification) {
        
        UIAlertView *alartView = [[UIAlertView alloc]initWithTitle:nil message:@"时间到" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        
        self.vibrate = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(Vibrate) userInfo:nil repeats:YES];
        
        NSString *string = notification.userInfo.allValues[0];
        
        NSInteger musicNumber = [string substringWithRange:NSMakeRange(string.length - 2, 2)].integerValue;
        
        NSString *path = [[NSBundle mainBundle] pathForResource:self.musicArr[musicNumber] ofType:@"mp3"];
        
        if (path) {
            //注册声音到系统
            NSURL *soundURL =[NSURL fileURLWithPath:path];
            OSStatus err = AudioServicesCreateSystemSoundID((__bridge CFURLRef)soundURL, &audio_queue);
            if(err!= kAudioServicesNoError){
                NSLog(@"Could not load %@,error code:%d",soundURL,err);
            }
        }
        
        AudioServicesPlaySystemSound((SystemSoundID)audio_queue); //开始播放声音
        
        AudioServicesAddSystemSoundCompletion(audio_queue, NULL, NULL, &playFinished, (__bridge void *)(self));
        
        [alartView show];
        
    }
    
}


- (void)Vibrate {
    
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);   //让手机震动
    
}

#pragma mark 点击确定取消震动音乐
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    [self.vibrate invalidate];
    AudioServicesDisposeSystemSoundID((SystemSoundID)audio_queue);
    AudioServicesRemoveSystemSoundCompletion((SystemSoundID)audio_queue);
    [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
    
}




-(void)changeRootViewController{
    self.window.rootViewController=_sideMenuViewController;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
